package org.colcon.web.model.vote;

import java.util.HashMap;
import java.util.Map;

import org.colcon.web.model.Vote;
import org.colcon.web.model.framework.IBallot;

public class SelectionVote extends Vote
{
	//TODO: validate vote is a member of choices
	
	public String getType(){return "selection_vote";}
	
	private static final long serialVersionUID = 4460583731256944110L;
	
	protected static final String
	
		// arguments
		CHOICES = "choices";
	
	private String choices;
	
	public SelectionVote()
	{
		this(new HashMap<String, String>());
	}
	
	public SelectionVote(Map<String, String> args)
	{
		this(
				args.get(PARENT), 
				args.get(ID), 
				args.get(TEXT),
				args.get(COMMAND),
				args.get(CHOICES), 
				args.get(CHILDREN)
		);
	}
	
	public SelectionVote(String parent, String id, String text, String command, String choices, String children)
	{
		super(parent, id, text, command, children);
		
		this.choices = choices;
	}
	
	public String[] getChoices()
	{
		if(choices == null || choices.isEmpty())
			return new String[0];
		
		return choices.split(" ");
	}
	
	public String getValue(IBallot[] ballots)
	{
		Map<String, Integer> count = new HashMap<String, Integer>();
		
		for(IBallot ballot : ballots)
		{
			String vote = ballot.getValue();
			
			if(!count.containsKey(vote))
				count.put(vote, 1);
			else
				count.put(vote, count.get(vote) + 1);
		}
		
		String winner = null;
		
		for(String str : count.keySet())
		{
			if(winner == null || count.get(str) > count.get(winner))
				winner = str;
			else if(count.get(str) == count.get(winner))
				winner = null;
		}
		
		return winner;
	}
	
	/*
	
	public boolean isValid(String vote)
	{
		for(String str : getChoices())
			if(vote.equals(str))
				return true;
		
		return false;
	}
	
	public String getValue()
	{
		Map<String, Integer> count = new HashMap<String, Integer>();
		
		for(IBallot ballot : getBallots())
		{
			String vote = ballot.getValue();
			
			if(!count.containsKey(vote))
				count.put(vote, 1);
			else
				count.put(vote, count.get(vote) + 1);
		}
		
		String winner = null;
		
		for(String str : count.keySet())
		{
			if(winner == null || count.get(str) > count.get(winner))
				winner = str;
			else if(count.get(str) == count.get(winner))
				winner = null;
		}
		
		return winner;
	}
	
	*/
}
